package cn.org.cute.ebocy.util;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;

public class FileCollection {
	
	private File folder;
	private FileFilter filter;
	
	private ArrayList files;
	
	public FileCollection(File folder)throws IOException{
		this(folder, null);
	}
	
	public FileCollection(File folder, FileFilter filter)throws IOException{
		
		this.folder = folder;
		this.filter = filter;
		
		if(!folder.exists()){
			throw new IOException("Folder not exists.");
		}
		
		files = new ArrayList();
		
		collectFile(0, "", folder);
		
	}
	
	public File getFolder(){
		
		return folder;
		
	}
	
	public FileFilter getFilter(){
		
		return filter;
		
	}
	
	public ArrayList getFiles(){
		
		return files;
		
	}
	
	public int getSize(){
		
		return files.size();
		
	}
	
	public RelativeFile getFile(int pos){
		
		return (RelativeFile) files.get(pos);
		
	}
	
	private void collectFile(int level, String path, File file){
		
		if(!accept(file)){
			return;
		}
		
		//if a directory, has been accepted.
		if(file.isDirectory()){
			String currPath = path + File.separatorChar + file.getName();
			int currLevel = level + 1;
			File[] currFiles = file.listFiles();
			for(int i=0; i<currFiles.length; i++){
				collectFile(currLevel, currPath, currFiles[i]);				
			}			
		}
		//is a file, has been accepted.
		else{
			files.add(new RelativeFile(level, path, file));
		}
		
	}
	
	protected boolean accept(File file){
		
		if(filter != null){
			return filter.accept(file);
		}
		return true;
		
	}
	
}
